package cn.huaqingcheng.tianshu.mybatis.type;

import cn.huaqingcheng.tianshu.common.core.model.AttributeMap;
import cn.huaqingcheng.tianshu.common.core.model.CommonConvert;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

@MappedTypes(AttributeMap.class)
public class AttributeMapTypeHandler extends BaseTypeHandler<AttributeMap<?>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, AttributeMap<?> parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, CommonConvert.INSTANCE.toJson(parameter), Types.OTHER);
    }

    @Override
    public AttributeMap<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return CommonConvert.INSTANCE.toMap(rs.getString(columnName));
    }

    @Override
    public AttributeMap<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return CommonConvert.INSTANCE.toMap(rs.getString(columnIndex));
    }

    @Override
    public AttributeMap<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return CommonConvert.INSTANCE.toMap(cs.getString(columnIndex));
    }

}
